const User = require('../models/user.model');
const Video = require('../models/video.model');
const Post = require('../models/post.model');
const Comment = require('../models/comment.model');
const Category = require('../models/category.model');
const ActivityLog = require('../models/activityLog.model'); 
const { calculateDateRange } = require('../utils/dateUtils'); 
const { toAbsoluteUrl } = require('../utils/urlUtils'); // 导入 URL 处理函数

// 获取仪表盘统计数据
exports.getStats = async (req, res) => {
  try {
    const today = new Date();
    const startOfToday = new Date(today.setHours(0, 0, 0, 0));
    const startOfYesterday = new Date(new Date().setDate(today.getDate() - 1)).setHours(0, 0, 0, 0);

    const totalUsers = await User.countDocuments();
    const newUsersToday = await User.countDocuments({ createdAt: { $gte: startOfToday } });
    const newUsersYesterday = await User.countDocuments({ createdAt: { $gte: startOfYesterday, $lt: startOfToday } });

    const totalVideos = await Video.countDocuments();
    const newVideosToday = await Video.countDocuments({ createdAt: { $gte: startOfToday } });
    const newVideosYesterday = await Video.countDocuments({ createdAt: { $gte: startOfYesterday, $lt: startOfToday } });

    const totalPosts = await Post.countDocuments();
    const newPostsToday = await Post.countDocuments({ createdAt: { $gte: startOfToday } });
    const newPostsYesterday = await Post.countDocuments({ createdAt: { $gte: startOfYesterday, $lt: startOfToday } });

    const totalComments = await Comment.countDocuments();
    const newCommentsToday = await Comment.countDocuments({ createdAt: { $gte: startOfToday } });
    const newCommentsYesterday = await Comment.countDocuments({ createdAt: { $gte: startOfYesterday, $lt: startOfToday } });

    const calculateTrend = (todayCount, yesterdayCount) => {
      if (yesterdayCount === 0) return todayCount > 0 ? 100 : 0;
      return ((todayCount - yesterdayCount) / yesterdayCount) * 100;
    };

    res.json({
      totalUsers,
      newUsers: newUsersToday,
      userTrend: calculateTrend(newUsersToday, newUsersYesterday),
      totalVideos,
      newVideos: newVideosToday,
      videoTrend: calculateTrend(newVideosToday, newVideosYesterday),
      totalPosts,
      newPosts: newPostsToday,
      postTrend: calculateTrend(newPostsToday, newPostsYesterday),
      totalComments,
      newComments: newCommentsToday,
      commentTrend: calculateTrend(newCommentsToday, newCommentsYesterday),
    });
  } catch (error) {
    console.error('Error fetching stats:', error);
    res.status(500).json({ message: '获取统计数据失败' });
  }
};

// 获取趋势数据
exports.getTrendStats = async (req, res) => {
  const { type = 'week' } = req.query; // 'week' or 'month'
  try {
    const { startDate, endDate, interval } = calculateDateRange(type);

    const dateAggregator = {
      $dateToString: {
        format: '%Y-%m-%d', // 统一按天聚合
        date: '$createdAt'
      }
    };

    const groupStage = {
      _id: dateAggregator,
      count: { $sum: 1 }
    };

    const sortStage = { $sort: { _id: 1 } };

    // 分别查询各个模型的聚合数据
    const [userResults, videoResults, postResults, commentResults] = await Promise.all([
      User.aggregate([
        { $match: { createdAt: { $gte: startDate, $lte: endDate } } },
        { $group: groupStage },
        sortStage
      ]),
      Video.aggregate([
        { $match: { createdAt: { $gte: startDate, $lte: endDate } } },
        { $group: groupStage },
        sortStage
      ]),
      Post.aggregate([
        { $match: { createdAt: { $gte: startDate, $lte: endDate } } },
        { $group: groupStage },
        sortStage
      ]),
      Comment.aggregate([
        { $match: { createdAt: { $gte: startDate, $lte: endDate } } },
        { $group: groupStage },
        sortStage
      ])
    ]);

    // 格式化数据以匹配 ECharts 需求
    const dates = [];
    const usersData = [];
    const videosData = [];
    const postsData = [];
    const commentsData = [];

    // 生成日期序列
    let currentDate = new Date(startDate);
    while (currentDate <= endDate) {
      dates.push(currentDate.toISOString().split('T')[0]);
      currentDate.setDate(currentDate.getDate() + 1);
    }

    // 创建 Map 以便快速查找
    const userMap = new Map(userResults.map(item => [item._id, item.count]));
    const videoMap = new Map(videoResults.map(item => [item._id, item.count]));
    const postMap = new Map(postResults.map(item => [item._id, item.count]));
    const commentMap = new Map(commentResults.map(item => [item._id, item.count]));

    // 填充数据
    dates.forEach(date => {
      usersData.push(userMap.get(date) || 0);
      videosData.push(videoMap.get(date) || 0);
      postsData.push(postMap.get(date) || 0);
      commentsData.push(commentMap.get(date) || 0);
    });

    res.json({
      dates,
      users: usersData,
      videos: videosData,
      posts: postsData,
      comments: commentsData,
    });

  } catch (error) {
    console.error(`Error fetching ${type} trend stats:`, error);
    res.status(500).json({ message: '获取趋势数据失败' });
  }
};

// 获取最近活动日志 (改为获取最近创建的内容)
exports.getRecentActivities = async (req, res) => {
  try {
    const limit = 5; 

    const recentUsers = await User.find().sort({ createdAt: -1 }).limit(limit).select('username createdAt');
    const recentVideos = await Video.find().sort({ createdAt: -1 }).limit(limit).select('title createdAt');
    const recentPosts = await Post.find().sort({ createdAt: -1 }).limit(limit).select('title createdAt');
    const recentComments = await Comment.find().sort({ createdAt: -1 }).limit(limit).select('content createdAt user').populate('user', 'username');

    const activities = [
      ...recentUsers.map(u => ({ _id: `user-${u._id}`, type: 'user', description: `新用户注册: ${u.username}`, createdAt: u.createdAt })),
      ...recentVideos.map(v => ({ _id: `video-${v._id}`, type: 'video', description: `新视频发布: ${v.title}`, createdAt: v.createdAt })),
      ...recentPosts.map(p => ({ _id: `post-${p._id}`, type: 'post', description: `新帖子发布: ${p.title}`, createdAt: p.createdAt })),
      ...recentComments.map(c => ({ _id: `comment-${c._id}`, type: 'comment', description: `新评论来自 ${c.user?.username || '未知用户'}: ${c.content ? c.content.substring(0, 30) + '...' : '[内容为空]'}`, createdAt: c.createdAt }))
    ];

    // 按时间倒序排序并截取最新的10条
    activities.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    const latestActivities = activities.slice(0, 10);

    res.json(latestActivities);
  } catch (error) {
    console.error('Error fetching recent activities:', error);
    res.status(500).json({ message: '获取最近活动失败' });
  }
};

// --- 用户管理 ---
exports.getUsers = async (req, res) => {
  const { page = 1, limit = 10, search = '', role = '', status = '' } = req.query;
  try {
    const query = {};
    if (search) {
      query.$or = [
        { username: { $regex: search, $options: 'i' } },
        { email: { $regex: search, $options: 'i' } },
      ];
    }
    if (role) query.role = role;
    if (status) query.status = status;

    const users = await User.find(query)
      .select('-password -watchHistory')
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .sort({ createdAt: -1 });

    const count = await User.countDocuments(query);

    // 处理头像 URL
    const processedUsers = users.map(user => {
      const userObj = user.toObject();
      if (userObj.avatar) {
        userObj.avatar = toAbsoluteUrl(userObj.avatar);
      }
      return userObj;
    });

    res.json({
      users: processedUsers,
      totalPages: Math.ceil(count / limit),
      currentPage: parseInt(page, 10),
      totalUsers: count
    });
  } catch (error) {
    console.error('Error fetching users:', error);
    res.status(500).json({ message: '获取用户列表失败' });
  }
};

exports.updateUserStatus = async (req, res) => {
  const { id } = req.params;
  const { status } = req.body; // 'active', 'inactive', 'banned'
  try {
    const user = await User.findByIdAndUpdate(id, { status }, { new: true });
    if (!user) return res.status(404).json({ message: '用户不存在' });
    // 记录活动日志 (可选)
    // await ActivityLog.create({ type: 'user', description: `用户 ${user.username} 状态更新为 ${status}`, userId: req.user.id });
    res.json(user);
  } catch (error) {
    console.error('Error updating user status:', error);
    res.status(500).json({ message: '更新用户状态失败' });
  }
};

exports.updateUserRole = async (req, res) => {
  const { id } = req.params;
  const { role } = req.body; // 'user', 'admin'
  try {
    const user = await User.findByIdAndUpdate(id, { role }, { new: true });
    if (!user) return res.status(404).json({ message: '用户不存在' });
    // 记录活动日志 (可选)
    // await ActivityLog.create({ type: 'user', description: `用户 ${user.username} 角色更新为 ${role}`, userId: req.user.id });
    res.json(user);
  } catch (error) {
    console.error('Error updating user role:', error);
    res.status(500).json({ message: '更新用户角色失败' });
  }
};

exports.deleteUser = async (req, res) => {
  const { id } = req.params;
  try {
    const user = await User.findByIdAndDelete(id);
    if (!user) return res.status(404).json({ message: '用户不存在' });
    res.json({ message: '用户删除成功' });
  } catch (error) {
    console.error('Error deleting user:', error);
    res.status(500).json({ message: '删除用户失败' });
  }
};

// 添加更新用户信息的方法
exports.updateUser = async (req, res) => {
  const { id } = req.params;
  const { username, email, role, status } = req.body;
  
  try {
    // 构建更新对象
    const updateData = {};
    if (username) updateData.username = username;
    if (email) updateData.email = email;
    if (role) updateData.role = role;
    if (status) updateData.status = status;
    
    console.log('正在更新用户:', id, '数据:', updateData);
    
    // 更新用户信息
    const user = await User.findByIdAndUpdate(
      id, 
      updateData,
      { new: true, runValidators: true }
    ).select('-password -watchHistory');
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 处理头像URL
    const userObj = user.toObject();
    if (userObj.avatar) {
      userObj.avatar = toAbsoluteUrl(userObj.avatar);
    }
    
    console.log('用户更新成功:', userObj);
    res.json({ user: userObj, message: '用户信息更新成功' });
    
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({ message: '更新用户信息失败', error: error.message });
  }
};

// --- 视频管理 ---
exports.getVideos = async (req, res) => {
  const { page = 1, limit = 10, search = '', category = '', status = '' } = req.query;
  try {
    const query = {};
    if (search) query.title = { $regex: search, $options: 'i' };
    if (category) query.category = category;
    if (status) query.status = status; // 'public', 'private', 'unlisted', 'processing', 'failed'

    const videos = await Video.find(query)
      .populate('user', 'username avatar')
      .populate('category', 'name')
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .sort({ createdAt: -1 });

    
    videos.forEach(video => {
      if (!video.formats || video.formats.length === 0) {
        video.formats = [{
          quality: 'original',
          url: video.videoUrl,
          size: 0
        }];
      }
    });

    const count = await Video.countDocuments(query);

    res.json({
      videos,
      totalPages: Math.ceil(count / limit),
      currentPage: page,
      totalVideos: count
    });
  } catch (error) {
    console.error('Error fetching videos:', error);
    res.status(500).json({ message: '获取视频列表失败' });
  }
};

exports.updateVideoStatus = async (req, res) => {
  const { id } = req.params;
  const { status } = req.body;
  try {
    const video = await Video.findByIdAndUpdate(id, { status }, { new: true });
    if (!video) return res.status(404).json({ message: '视频不存在' });
    
    res.json(video);
  } catch (error) {
    console.error('Error updating video status:', error);
    res.status(500).json({ message: '更新视频状态失败' });
  }
};

// 更新视频信息
exports.updateVideo = async (req, res) => {
  const { id } = req.params;
  const { title, description, category, tags, privacy } = req.body;
  try {
    const video = await Video.findByIdAndUpdate(
      id, 
      { title, description, category, tags, privacy }, 
      { new: true }
    );
    if (!video) return res.status(404).json({ message: '视频不存在' });
    res.json(video);
  } catch (error) {
    console.error('Error updating video:', error);
    res.status(500).json({ message: '更新视频失败' });
  }
};

// 创建新视频
exports.createVideo = async (req, res) => {
  try {
    const { title, description, category, tags = [], userId, privacy = 'public', videoUrl } = req.body;
    
    // 验证必填字段
    if (!title || !description || !userId) {
      return res.status(400).json({ message: '标题、描述和用户ID为必填项' });
    }
    
    // 检查用户是否存在
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 创建视频对象
    const videoData = {
      title,
      description,
      category,
      tags,
      user: userId,
      privacy,
      status: 'ready',
      processingProgress: 100
    };
    

    if (videoUrl) {
      videoData.videoUrl = videoUrl;
      
      // 添加格式信息
      const fs = require('fs');
      const path = require('path');
      const filePath = path.join(__dirname, '..', '..', videoUrl.replace(/^\/uploads/, 'uploads'));
      
      let fileSize = 0;
      if (fs.existsSync(filePath)) {
        fileSize = fs.statSync(filePath).size;
      }
      
      videoData.formats = [{
        quality: 'original',
        url: videoUrl,
        size: fileSize
      }];
    }
    
    // 创建视频
    const video = new Video(videoData);
    await video.save();
    
    res.status(201).json({
      message: '视频创建成功',
      video
    });
  } catch (error) {
    console.error('Error creating video:', error);
    res.status(500).json({ message: '创建视频失败', error: error.message });
  }
};

exports.deleteVideo = async (req, res) => {
  const { id } = req.params;
  try {
    const video = await Video.findByIdAndDelete(id);
    if (!video) return res.status(404).json({ message: '视频不存在' });

    res.json({ message: '视频删除成功' });
  } catch (error) {
    console.error('Error deleting video:', error);
    res.status(500).json({ message: '删除视频失败' });
  }
};

// --- 帖子管理 ---
exports.getPosts = async (req, res) => {
  const { page = 1, limit = 10, search = '', status = '' } = req.query;
  try {
    const query = {};
    if (search) {
      query.$or = [
        { title: { $regex: search, $options: 'i' } },
        { content: { $regex: search, $options: 'i' } },
      ];
    }
    if (status) query.status = status; 

    const posts = await Post.find(query)
      .populate('user', 'username avatar')
      .populate('category', 'name') 
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .sort({ createdAt: -1 });

    const count = await Post.countDocuments(query);

    res.json({
      posts,
      totalPages: Math.ceil(count / limit),
      currentPage: page,
      totalPosts: count
    });
  } catch (error) {
    console.error('Error fetching posts:', error);
    res.status(500).json({ message: '获取帖子列表失败' });
  }
};

// 创建新帖子
exports.createPost = async (req, res) => {
  try {
    const { title, content, category, tags = [], userId, status = 'published' } = req.body;
    
    // 验证必填字段
    if (!title || !content || !userId) {
      return res.status(400).json({ message: '标题、内容和用户ID为必填项' });
    }
    
    // 检查用户是否存在
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 创建帖子
    const post = new Post({
      title,
      content,
      category,
      tags,
      user: userId,
      status
    });
    
    await post.save();
    
    res.status(201).json({
      message: '帖子创建成功',
      post
    });
  } catch (error) {
    console.error('Error creating post:', error);
    res.status(500).json({ message: '创建帖子失败', error: error.message });
  }
};

// 更新帖子
exports.updatePost = async (req, res) => {
  const { id } = req.params;
  const { title, content, category, tags, status } = req.body;
  
  try {
    const post = await Post.findByIdAndUpdate(
      id,
      { title, content, category, tags, status },
      { new: true }
    );
    
    if (!post) return res.status(404).json({ message: '帖子不存在' });
    
    res.json({
      message: '帖子更新成功',
      post
    });
  } catch (error) {
    console.error('Error updating post:', error);
    res.status(500).json({ message: '更新帖子失败' });
  }
};

exports.updatePostStatus = async (req, res) => {
  const { id } = req.params;
  const { status } = req.body;
  try {
    const post = await Post.findByIdAndUpdate(id, { status }, { new: true });
    if (!post) return res.status(404).json({ message: '帖子不存在' });
  
    res.json(post);
  } catch (error) {
    console.error('Error updating post status:', error);
    res.status(500).json({ message: '更新帖子状态失败' });
  }
};

exports.deletePost = async (req, res) => {
  const { id } = req.params;
  try {
    const post = await Post.findByIdAndDelete(id);
    if (!post) return res.status(404).json({ message: '帖子不存在' });
    res.json({ message: '帖子删除成功' });
  } catch (error) {
    console.error('Error deleting post:', error);
    res.status(500).json({ message: '删除帖子失败' });
  }
};

// --- 评论管理 ---
exports.getComments = async (req, res) => {
  const { page = 1, limit = 10, search = '', type = '', status = '' } = req.query;
  try {
    const query = {};
    if (search) query.text = { $regex: search, $options: 'i' };
    if (type) query.targetType = type; // 'video', 'post'
    if (status) query.status = status; // 'active', 'hidden'

    const comments = await Comment.find(query)
      .populate('user', 'username avatar')
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .sort({ createdAt: -1 });

    const count = await Comment.countDocuments(query);

    // 收集所有目标ID
    const videoIds = [];
    const postIds = [];
    
    comments.forEach(comment => {
      if (comment.targetType === 'video') {
        videoIds.push(comment.targetId);
      } else if (comment.targetType === 'post') {
        postIds.push(comment.targetId);
      }
    });
    
    // 批量查询视频和帖子信息
    const [videos, posts] = await Promise.all([
      videoIds.length > 0 ? Video.find({ _id: { $in: videoIds } }).select('title') : [],
      postIds.length > 0 ? Post.find({ _id: { $in: postIds } }).select('title') : [],
    ]);
    
    // 创建ID到标题的映射
    const videoMap = new Map(videos.map(v => [v._id.toString(), v]));
    const postMap = new Map(posts.map(p => [p._id.toString(), p]));
    
    // 处理评论数据添加标题信息
    const processedComments = comments.map(comment => {
      const commentObj = comment.toObject();
      
      // 添加目标标题
      if (comment.targetType === 'video' && videoMap.has(comment.targetId.toString())) {
        commentObj.targetTitle = videoMap.get(comment.targetId.toString()).title;
      } else if (comment.targetType === 'post' && postMap.has(comment.targetId.toString())) {
        commentObj.targetTitle = postMap.get(comment.targetId.toString()).title;
      } else {
        commentObj.targetTitle = '已删除的内容';
      }
      
      // 安全处理用户头像
      if (commentObj.user && commentObj.user.avatar) {
        try {
          commentObj.user.avatar = toAbsoluteUrl(commentObj.user.avatar);
        } catch (error) {
          commentObj.user.avatar = '/default-avatar.png';
        }
      }
      
      return commentObj;
    });

    res.json({
      comments: processedComments,
      totalPages: Math.ceil(count / limit),
      currentPage: page,
      totalComments: count
    });
  } catch (error) {
    console.error('Error fetching comments:', error);
    res.status(500).json({ message: '获取评论列表失败' });
  }
};

exports.updateCommentStatus = async (req, res) => {
  const { id } = req.params;
  const { status } = req.body;
  
  // 确保状态值有效
  if (!['active', 'hidden', 'deleted'].includes(status)) {
    return res.status(400).json({ message: '无效的状态值' });
  }
  
  try {
    const comment = await Comment.findByIdAndUpdate(id, { status }, { new: true });
    if (!comment) return res.status(404).json({ message: '评论不存在' });
    // 记录活动日志 (可选)
    res.json(comment);
  } catch (error) {
    console.error('Error updating comment status:', error);
    res.status(500).json({ message: '更新评论状态失败' });
  }
};

exports.deleteComment = async (req, res) => {
  const { id } = req.params;
  try {
    const comment = await Comment.findByIdAndDelete(id);
    if (!comment) return res.status(404).json({ message: '评论不存在' });
    // 记录活动日志 (可选)
    res.json({ message: '评论删除成功' });
  } catch (error) {
    console.error('Error deleting comment:', error);
    res.status(500).json({ message: '删除评论失败' });
  }
};

// 批量更新评论状态
exports.batchUpdateCommentsStatus = async (req, res) => {
  const { ids, status } = req.body;
  
  // 验证参数
  if (!ids || !Array.isArray(ids) || ids.length === 0) {
    return res.status(400).json({ message: '请提供评论ID列表' });
  }
  
  if (!status || !['active', 'hidden', 'deleted'].includes(status)) {
    return res.status(400).json({ message: '无效的状态值' });
  }
  
  try {
    const result = await Comment.updateMany(
      { _id: { $in: ids } },
      { $set: { status } }
    );
    
    if (result.matchedCount === 0) {
      return res.status(404).json({ message: '未找到任何匹配的评论' });
    }
    
    res.json({
      message: `已成功更新 ${result.modifiedCount} 条评论的状态`,
      modifiedCount: result.modifiedCount
    });
  } catch (error) {
    console.error('Error batch updating comment status:', error);
    res.status(500).json({ message: '批量更新评论状态失败' });
  }
};

// 批量删除评论
exports.batchDeleteComments = async (req, res) => {
  const { ids } = req.body;
  
  // 验证参数
  if (!ids || !Array.isArray(ids) || ids.length === 0) {
    return res.status(400).json({ message: '请提供评论ID列表' });
  }
  
  try {
    // 先收集所有要删除的评论及其子评论
    let allIdsToDelete = [...ids];
    
    // 查找所有子评论
    for (const commentId of ids) {
      const childComments = await Comment.find({ parentId: commentId }).select('_id');
      const childIds = childComments.map(c => c._id);
      allIdsToDelete = [...allIdsToDelete, ...childIds];
    }
    
    // 执行删除
    const result = await Comment.deleteMany({ _id: { $in: allIdsToDelete } });
    
    if (result.deletedCount === 0) {
      return res.status(404).json({ message: '未找到任何匹配的评论' });
    }
    
    res.json({
      message: `已成功删除 ${result.deletedCount} 条评论`,
      deletedCount: result.deletedCount
    });
  } catch (error) {
    console.error('Error batch deleting comments:', error);
    res.status(500).json({ message: '批量删除评论失败' });
  }
};

// --- 分类管理 ---
exports.getCategories = async (req, res) => {
  const { page = 1, limit = 10, search = '' } = req.query;
  try {
    const query = {};
    if (search) query.name = { $regex: search, $options: 'i' };

    const categories = await Category.find(query)
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .sort({ order: 1, createdAt: -1 }); // 按排序字段和创建时间排序

    const count = await Category.countDocuments(query);

    res.json({
      categories,
      totalPages: Math.ceil(count / limit),
      currentPage: page,
      totalCategories: count
    });
  } catch (error) {
    console.error('Error fetching categories:', error);
    res.status(500).json({ message: '获取分类列表失败' });
  }
};

exports.createCategory = async (req, res) => {
  const { name, path, icon, order, description } = req.body;
  try {
    const newCategory = new Category({ name, path, icon, order, description });
    await newCategory.save();
    // 记录活动日志 (可选)
    res.status(201).json(newCategory);
  } catch (error) {
    console.error('Error creating category:', error);
    res.status(500).json({ message: '创建分类失败' });
  }
};

exports.updateCategory = async (req, res) => {
  const { id } = req.params;
  const { name, path, icon, order, description, status } = req.body;
  try {
    const updatedCategory = await Category.findByIdAndUpdate(id, 
      { name, path, icon, order, description, status }, 
      { new: true, runValidators: true }
    );
    if (!updatedCategory) return res.status(404).json({ message: '分类不存在' });
    // 记录活动日志 (可选)
    res.json(updatedCategory);
  } catch (error) {
    console.error('Error updating category:', error);
    res.status(500).json({ message: '更新分类失败' });
  }
};

exports.deleteCategory = async (req, res) => {
  const { id } = req.params;
  try {
    // 检查是否有视频或帖子关联此分类
    const videoCount = await Video.countDocuments({ category: id });
    const postCount = await Post.countDocuments({ category: id }); // 假设帖子有关联分类
    if (videoCount > 0 || postCount > 0) {
      return res.status(400).json({ message: '无法删除，该分类下存在内容' });
    }

    const deletedCategory = await Category.findByIdAndDelete(id);
    if (!deletedCategory) return res.status(404).json({ message: '分类不存在' });
    // 记录活动日志 (可选)
    res.json({ message: '分类删除成功' });
  } catch (error) {
    console.error('Error deleting category:', error);
    res.status(500).json({ message: '删除分类失败' });
  }
};

// --- 系统设置 ---
exports.getSettings = async (req, res) => {
  try {
    const Setting = require('../models/setting.model');
    const settings = await Setting.findOne();
    if (!settings) {
      const defaultSettings = new Setting();
      await defaultSettings.save();
      return res.json({ success: true, settings: defaultSettings });
    }
    res.json({ success: true, settings });
  } catch (error) {
    console.error('Error fetching settings:', error);
    res.status(500).json({ success: false, message: '获取系统设置失败' });
  }
};

exports.updateSettings = async (req, res) => {
  try {
    const Setting = require('../models/setting.model');
    let settings = await Setting.findOne();
    
    if (!settings) {
      settings = new Setting();
    }
    
    // 更新设置字段
    const updatableFields = [
      'siteName', 'siteDescription', 'icpNumber',
      'maxVideoSize', 'allowedVideoFormats',
      'enableComments', 'commentNeedsReview', 'commentInterval',
      'enableRegistration', 'defaultUserRole', 'defaultUserStatus',
      'videoNeedsReview', 'defaultVideoStatus', 'enableVideoDownload',
      'storageType', 'storageConfig',
      'emailConfig',
      'enableCache', 'cacheExpiration',
      'autoBackup', 'backupInterval', 'maxBackupFiles'
    ];
    
    updatableFields.forEach(field => {
      if (req.body[field] !== undefined) {
        settings[field] = req.body[field];
      }
    });
    
    await settings.save();
    res.json({ success: true, settings });
  } catch (error) {
    console.error('Error updating settings:', error);
    if (error.name === 'ValidationError') {
      return res.status(400).json({
        success: false,
        message: '设置验证失败',
        errors: Object.values(error.errors).map(err => err.message)
      });
    }
    res.status(500).json({ success: false, message: '更新系统设置失败' });
  }
};